import { BASE_URL, TOKENNAME, USER_INFO, SHOP_INFO, USER_TYPE } from "@/config.js"
import { types } from "@/store/lang.js"
import { Info, Banner, categoryPage, notifyUserNotifyInfo } from '@/api/base.js'
import { userInfo } from '@/api/personal.js'
import { merchantInfo } from '@/api/merchant/merchant.js'
import { actionSign, actionCheckSign } from "@/api/action"
// 通用类 - 针对设置项
export default {
	state: {
		types,
		keyboardHeight: 0,
		userInfo: {},
		shopInfo: {},
		
		isFirst: true,
		
		contactPhone: '',
		otherLink: '',
		otherLinkUrls: {
			login: '/pages/first/login/login',
			register: '/pages/first/register/register'
		},
		
		tabbars: ['user', 'user', 'user', 'user', 'user', 'shop', 'shop', 'shop', 'shop'],
		
		advertList: [],
		
		shopCategory: [],
		commodityCategory: [],
		
		locationStatus: 0, // 是否已经定位
		locationLatlng: '',
		contactStatus: 0, // 是否已开启通话权限
		
		signStatus: true, // 默认已经签到
		messageInfo: {}
	},
	mutations: {
		UPDATE_KEYBOARD_HEIGHT(state, height = 0) {
			uni.$emit('keyboardchange', height)
			state.keyboardHeight = height
		},
		// 根据类型，更新tabbar数据
		UPDATE_TABBAR_VISIBLE_TYPE(state, accountType = 'user') {
			uni.setStorageSync(USER_TYPE, accountType)
			// 声明起始坐标
			try{
				state.tabbars.map((item, index) => {
					uni.setTabBarItem({
						visible: accountType === item,
						index
					})
				})
			}catch(e){
				state.tabbars.map((item, index) => {
					uni.setTabBarItem({
						visible: accountType === item,
						index
					})
				})
			}
		},
		// 保存token和个人信息
		UPDATE_USER_INFO(state, data = {}) {
			state.userInfo = data
			if (data.token) {
				uni.setStorageSync(USER_INFO, JSON.stringify(data))
				uni.setStorageSync(TOKENNAME, data.token || '')
			} else {
				uni.removeStorageSync(USER_INFO)
				uni.removeStorageSync(SHOP_INFO)
				uni.removeStorageSync(TOKENNAME)
			}
		},
		// 保存商家信息
		UPDATE_SHOP_INFO(state, data = {}) {
			state.shopInfo = data
			uni.setStorageSync(SHOP_INFO, JSON.stringify(data))
		},
		// 用户进入首页前判断，如果没完善基本信息则进入对应的基本信息页面
		BEFORE_INTO_INDEX(state, pageKey = 'blank') {
			let otherLinkQuery = (state.otherLink || '').split('&')
			let typeIndex = otherLinkQuery.findIndex(item => item.indexOf('type=') > -1)
			if (typeIndex > -1) {
				let typeStr = otherLinkQuery[typeIndex]
				let page = state.otherLinkUrls[typeStr.split('=')[1]]
				if (page) {
					state.otherLink = ''
					uni.reLaunch({
						url: page + `?${ otherLinkQuery.filter(item => item !== typeStr).join('&') }`
					})
					return 
				}
			}
			let userInfo = uni.getStorageSync(USER_INFO)
			let userType = uni.getStorageSync(USER_TYPE)
			if (userInfo) {
				userInfo = JSON.parse(userInfo)
				const { nick, sex, birthday } = userInfo
				// 关键数据没有的时候进入登录导航阶段
				let active = !nick ? 1 : !sex ? 2 : !birthday ? 3 : 0
				if (active) {
					let url = `/pages/first/loginGuide/main/main?active=${ active }`
					
					if (pageKey === 'blank') {
						uni.reLaunch({ url })
					} else {
						uni.navigateTo({ url })
					}
					return
				}
			}
			if (state.advertList.length && pageKey === 'blank') {
				uni.reLaunch({
					url: `/pages/once/ad/ad`
				})
			} else if (userInfo) {
				// 需要做判断进入的是商家还是用户
				uni.reLaunch({
					url: `/pages/tabbar/${ userType || 'user' }/index/index`
				})
			} else {
				uni.reLaunch({
					url: `/pages/first/select/select`
				})
			}
		},
		// 更新商家分类
		UPDATE_CATEGORY(state, { data, dataType }) {
			if (dataType === 1) {
				state.shopCategory = data
			} else {
				state.commodityCategory = data
			}
		},
		// 更新商品分类
		UPDATE_COMMODITY_CATEGORY(state, data) {
			state.commodityCategory = data
		},
		// 更新客服电话
		UPDATE_CONTEACT_PHONE(state, data) {
			state.contactPhone = data
		},
		// 更新签到状态
		UPDATE_USER_SIGN_STATUS(state, data) {
			state.signStatus = data
		},
		// 更新广告页
		UPDATE_USER_ADVERT(state, data) {
			state.advertList = data
		},
		// 更新定位状态
		UPDATE_LOCATION_STATUS(state, data) {
			state.locationStatus = data ? 1 : 0
		},
		// 更新定位
		UPDATE_LOCATION_LATLNG(state, data) {
			state.locationLatlng = data || ''
		},
		// 更新通话状态
		UPDATE_CONTACT_STATUS(state, data) {
			state.contactStatus = data
		},
		// 更新消息
		UPDATE_MESSAGE_INFO(state, data) {
			state.messageInfo = data || {}
		},
		// 初始化第三方链接
		INIT_OTHER_LINK(state, data) {
			state.otherLink = data || ''
		},
		// 更新是否是第一次
		ONSHOW_FIRST(state, data) {
			state.isFirst = data
		}
	},
	actions: {
		// 初始化广告
		initAdvert({ state, commit }, data) {
			return Banner({ type: 1 }).then((result) => {
				commit('UPDATE_USER_ADVERT', result.map(item => ({ ...item, image: BASE_URL + item.imgUrl })))
				return result
			}).catch(() => ([]))
		},
		// 获取分类列表
		initCategory({ state, commit }, dataType) {
			// 获取类型-商家
			categoryPage({ dataType }).then((result) => {
				commit('UPDATE_CATEGORY', { data: result, dataType })
			})
		},
		// 更新用户信息
		updateUserInfo({ state, commit }) {
			return new Promise((resolve, reject) => {
				userInfo({}).then((result) => {
					result = {...state.userInfo, ...result, ...result.userExtend}
					commit('UPDATE_USER_INFO', result)
					actionCheckSign({}).then(data => {
						commit('UPDATE_USER_SIGN_STATUS', data)
					})
					resolve(1)
				}).catch(() => {
					reject(0)
				})
			})
		},
		// 更新商家信息
		updateShopInfo({ state, commit }) {
			return new Promise((resolve, reject) => {
				merchantInfo({}).then((result) => {
					result = {...result}
					commit('UPDATE_SHOP_INFO', result)
					resolve(1)
				}).catch(() => {
					reject(0)
				})
			})
		},
		// 初始化客服电话
		initContactPhone({ state, commit }) {
			// 获取类型-商品
			Info({ key: 'key.kf.hotline' }).then((result) => {
				commit('UPDATE_CONTEACT_PHONE', result.content || '')
			})
		},
		// 更新签到
		updateSign({ state, commit }) {
			return actionSign({}).then((data) => {
				uni.showToast({
					icon: 'none',
					title: '签到成功'
				})
				commit('UPDATE_USER_SIGN_STATUS', 1)
			})
		},
		// 更新消息
		updateMessage({ state, commit }) {
			return new Promise((resolve, reject) => {
				notifyUserNotifyInfo({}).then((result) => {
					commit('UPDATE_MESSAGE_INFO', result)
					resolve(1)
				}).catch(() => {
					reject(0)
				})
			})
		}
	}
}
